package org.example.component;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import dev.langchain4j.data.message.ChatMessage;
import dev.langchain4j.data.message.ChatMessageDeserializer;
import dev.langchain4j.data.message.ChatMessageSerializer;
import dev.langchain4j.store.memory.chat.ChatMemoryStore;
import org.example.pojo.Messages;
import org.example.service.MessagesService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;

@Repository
public class MysqlChatMemoryStore implements ChatMemoryStore 
{
	@Autowired
	MessagesService messagesService;

	/**
	 * @param o 为 memoryId
	 * @return
	 */

	@Override
	public List<ChatMessage> getMessages(Object o) {
		//获取
		QueryWrapper qw = new QueryWrapper<>();
		qw.eq("memory_id",o);
		Messages one = messagesService.getOne(qw);
		List<ChatMessage> chatMessages = List.of();
		if(one != null) 
			chatMessages = ChatMessageDeserializer.messagesFromJson(one.getJsonText());

		return chatMessages;
	}

	@Override
	public void updateMessages(Object o, List<ChatMessage> list) 
	{
		//更新会话消息
		//把list数据转换为json数据
		String s = ChatMessageSerializer.messagesToJson(list);
		//把json数据存储到mysql中
		Messages messages = new Messages();
		messages.setMemoryId(o.toString());
		messages.setJsonText(s);
		QueryWrapper qw = new QueryWrapper<>();
		qw.eq("memory_id",o);
		messagesService.saveOrUpdate(messages,qw);
	}

	@Override
	public void deleteMessages(Object o) {
		QueryWrapper qw = new QueryWrapper<>();
		qw.eq("memory_id",o);
		
		messagesService.remove(qw);
	}
}
